from fastapi import FastAPI, HTTPException
from fastapi.responses import JSONResponse
from starlette.middleware.exceptions import ExceptionMiddleware


def register_exception_handler(app: FastAPI):
    app.add_middleware(ExceptionMiddleware,
                       handlers={HTTPException: global_exception_handler, Exception: global_exception_handler})


# 全局异常
async def global_exception_handler(request, exc):
    if exc.status_code == 500:
        err_msg = 'Server Internal Error'
    else:
        err_msg = exc.detail
    return JSONResponse({
        'code': exc.status_code,
        'message': err_msg,
    })


global_exception_handlers = {
    HTTPException: global_exception_handler,
    # RequestValidationError: validate_exception_handler
}
